package com.loser.gateway.netty.biz;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.loser.gateway.utils.ChannelUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;

/**
 * @Desc
 * @Author loser
 * @Date 2022/12/7
 **/
@Slf4j
public class WebSocketNettyServerRealIpHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        String oldIp = ChannelUtils.getIp(ctx.channel());
        if (StringUtils.isEmpty(oldIp)) {
            if (msg instanceof FullHttpRequest) {
                HttpHeaders headers = ((FullHttpRequest) msg).headers();
                String ip = getIp(headers);
                if (StringUtils.isNotEmpty(ip)) {
                    ChannelUtils.addRealIp(ctx.channel(), ip);
                }
                log.info("WebSocketNettyServerIpHandler-channelRead-获取IP是:{}", ip);
            }
        }
        ctx.fireChannelRead(msg);

    }

    private String getIp(HttpHeaders headers) {

        log.info("WebSocketNettyServerIpHandler-getIp-headers:{}", JSONUtil.parse(headers));
        String ip = headers.get("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.get("Proxy-Client-IP");

        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.get("WL-Proxy-Client-IP");

        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.get("HTTP_CLIENT_IP");

        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.get("HTTP_X_FORWARDED_FOR");

        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.get("X-Real-IP");

        }
        return ip;

    }

}
